<?php
namespace app\api\controller;

use think\Controller;
use think\Db;


/**
 * 微信公众号开发
 */
class Weixin extends Controller
{
    public $appid       = '';
    public $appsecret   = '';
    public $token       = 'TOKEN';

    /**
     * 构造方法
     */
    public function __construct()
    {
        $res = Db::name('option')->where('option_name', 'wx')->find();
        $wxConfig = json_decode($res['option_value'], true);

        $this->appsecret    = $wxConfig['appsecret'];
        $this->appid        = $wxConfig['appid'];
        $this->token        = $wxConfig['Token'];

        // 首次配置验证签名
        /*if($_GET["echostr"] && $_GET["signature"] && $_GET["timestamp"] && $_GET["nonce"]){
            // 验证签名
            $this->valid();
        }*/

        $this->responseMsg();


    }


    /**
     * 验证签名
     */
    public function valid(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    /**
     * 用户信息处理
     */
    public function responseMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            $fromUsername   = $postObj->FromUserName;
            $toUsername     = $postObj->ToUserName;
            $keyword        = trim($postObj->Content);
            $time           = time();
            $RX_TYPE        = trim($postObj->MsgType);

            if($RX_TYPE == 'text'){
                if(!empty($keyword)){

                    $textTpl =
                        "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                        </xml>";

                    $msgType = 'text';
                    $url = "http://www.tuling123.com/openapi/api?key=9009fc44f168cfc7055c8a469821ce9b&info={$keyword}";
                    $str = file_get_contents($url);
                    $json = json_decode($str);
                    $contentStr = $json -> text;
                    $contentStr = str_replace('帮帮的图图' , '美男子' , $contentStr);
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

                    // 记录数据
                    $data['keyword']    = $keyword;
                    $data['reply']      = $contentStr;
                    $data['create_time']= time();
                    $data['userinfo']   = $fromUsername;

                    Db("dd_robot")->insert($data);

                    echo $resultStr;

                }else{
                    echo "Input something...";
                }
            }else{
                echo "Input something...";
            }
        }else{
            echo "";
            exit;
        }
    }

    /**
     * 验证签名
     */
    private function checkSignature(){

        $signature  = $_GET["signature"];
        $timestamp  = $_GET["timestamp"];
        $nonce      = $_GET["nonce"];

        $token      = $this->token;

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


}
